package com.xiaoyang.ssyx.acl.controller;

import com.xiaoyang.ssyx.acl.service.PermissionService;
import com.xiaoyang.ssyx.common.result.Result;
import com.xiaoyang.ssyx.model.acl.Permission;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @AUTHOR XiaoYang
 * @DATE 2023/6/14-16:26
 * @DESCRIPTION TODO
 */
@RestController
@RequestMapping("/admin/acl/permission")
@Api(tags = "菜单管理")
//@CrossOrigin //跨域
public class PermissionController {
    @Autowired
    private PermissionService permissionService;

    /*
    url: `${api_name}/toAssign/${roleId}`,
    method: 'get'
    */
    @ApiOperation("查看角色权限列表")
    @GetMapping("toAssign/{roleId}")
    public Result toAssign(@PathVariable Long roleId){
        //返回的map集合中包含两部分数据 所有角色权限 和 为用户分配权限列表
        //List<Permission> list = permissionService.getPermissionByRoleId(roleId);
        Map<String,Object> map = permissionService.getPermissionByRoleId(roleId);
        return Result.ok(map);
    }
    /*
      url: `${api_name}/doAssign`,
      method: "post",
      params: {roleId, permissionId}
     */
    @ApiOperation("给角色授权")
    @PostMapping("doAssign")
    public Result doAssign(@RequestParam Long roleId,
                           @RequestParam Long[] permissionId){
        permissionService.saveAdminRole(roleId,permissionId);
        return Result.ok(null);
    }

    //1、查询所有菜单
    @ApiOperation("查询所有菜单")
    @GetMapping
    public Result list(){
        List<Permission> list = permissionService.queryAllPermission();
        return Result.ok(list);
    }

    //2、添加菜单
    @ApiOperation("添加菜单")
    @PostMapping("save")
    public Result save(@RequestBody Permission permission){
        boolean isSuccess = permissionService.save(permission);
        if (isSuccess){
            return Result.ok(null);
        }else {
            return Result.fail(null);
        }
    }

    //3、修改菜单
    @ApiOperation("修改菜单")
    @PutMapping("update")
    public Result update(@RequestBody Permission permission){
        boolean isSuccess = permissionService.updateById(permission);
        if (isSuccess){
            return Result.ok(null);
        }else {
            return Result.fail(null);
        }
    }

    //4、删除菜单
    @ApiOperation("删除菜单")
    @DeleteMapping("remove/{id}")
    public Result remove(@PathVariable Long id){
        boolean isSuccess = permissionService.removeChildById(id);
        if (isSuccess){
            return Result.ok(null);
        }else {
            return Result.fail(null);
        }
    }
}
